package com.crealth.manager;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;
import com.crealth.Config;
import com.crealth.db.SipConfigDb;
import com.crealth.db.UserDb;
import com.crealth.handler.ResponseMsgQueue;
import com.crealth.memcached.UserCached;
import com.crealth.model.SipAccountModel;
import com.crealth.model.SipConfigModel;
import com.crealth.model.UserModel;
import com.crealth.msg.NetMessageData;
import com.crealth.utils.Utils;

public class SipAccountManager {
	private static Integer usedSipAct = 0;
	private static Integer usedIncomingSipAct = 0;
	private static Map<Integer, Integer> comUsedSipAct = 
			new HashMap<Integer, Integer>();
	private static Map<Integer, Integer> comIncomingUsedSipAct = 
			new HashMap<Integer, Integer>();
	private static List<SipConfigModel> allSipConfig;
	private static SipConfigModel defaultSipConfig;
	public static Map<Integer, SipConfigModel> companySipConfig;
	public static Map<String, SipConfigModel> cityNameSipConfig;
	
	public static void loadSipConfig() {
		Config.sipDispatchType = UserDb.selectSipDispatchType();
		
		allSipConfig = SipConfigDb.selectAllSipConfig();
		defaultSipConfig = null;
		companySipConfig = null;
		cityNameSipConfig = null;
		if (allSipConfig == null || allSipConfig.size() == 0) {
			return;
		}
		companySipConfig = new HashMap<Integer, SipConfigModel>();
		cityNameSipConfig = new HashMap<String, SipConfigModel>();
		for (SipConfigModel sip : allSipConfig) {
			if (sip.getCompanyID() <= 0 && sip.getCityName().equals("")) {
				defaultSipConfig = sip;
				continue;
			}
			if (sip.getCompanyID() > 0) {
				companySipConfig.put(sip.getCompanyID(), sip);
			}
			if (sip.getCityName().length() > 0) {
				cityNameSipConfig.put(sip.getCityName(), sip);
			}
		}
	}
	
	public static void dispatchSipAccount() {
		if (Utils.isWindows()) {
			return;
		}
		if (Config.sipDispatchType == 0) {
			if (defaultSipConfig != null) {
				Config.sipServerIP = defaultSipConfig.getSipServer();
				Config.sipAccount = defaultSipConfig.getSipAccount();
				Config.sipPwd = defaultSipConfig.getSipPwd();
				Config.incomingSipIP = defaultSipConfig.getInSipServer();
				Config.incomingSipAccount = defaultSipConfig.getInSipAccount();
				Config.incomingSipPwd = defaultSipConfig.getInSipPwd();
			}
			reDistributeSipAct();
			sendAllUserSipAccount();
			return;
		}
		
		if (Config.sipDispatchType == 1) {  //  按城市分派
			distributeSipByCityName();
			sendAllUserSipAccount();
			return;
		}
		
		if (Config.sipDispatchType == 2) {  //  按公司分派
			distributeSipByCompany();
			sendAllUserSipAccount();
		}
		
	}
	
	private static void reDistributeSipAct() {
		if ( Utils.isWindows() ) {
			return;
		}
		try {
			int sipActBeginID = Integer.valueOf(Config.sipAccount);
			usedSipAct = sipActBeginID;
			if (Config.incomingSipIP.length() > 0) {
				int incomingSipActBeginID = Integer.valueOf(Config.incomingSipAccount);
				usedIncomingSipAct = incomingSipActBeginID;
			}
		} catch (NumberFormatException e) {
		}
		
		List<UserModel> allUser = UserDb.selectAllUser();
		SipAccountModel sipObj = new SipAccountModel(Config.sipServerIP, usedSipAct, Config.sipPwd);
		SipAccountModel inSipObj = new SipAccountModel(Config.incomingSipIP, usedIncomingSipAct, Config.incomingSipPwd);
		for (UserModel model : allUser) {
			updateUserSipAct(model, sipObj, inSipObj);
		}
		usedSipAct = sipObj.getnSipAct();
		usedIncomingSipAct = inSipObj.getnSipAct();
	}
	
	public static boolean updateUserSipAct(UserModel user, SipAccountModel sipObj,
			SipAccountModel inSipObj) {
		if (user.getFixedSip() == 1) {
			return false;
		}
		int userID = user.getId();
		if (user.getStaffStatus() == 6) {
			UserDb.updateSipAccountByID(userID, "", "", "", "", "", "");
			return false;
		}
		if ( !user.needSipAccount() ) {
			UserDb.updateSipAccountByID(userID, "", "", "", "", "", "");
			return false;
		}
		
		String sipSvr = sipObj.getSipServer();
		Integer sipAct = sipObj.getnSipAct();
		String sipPwd = sipObj.getSipPwd();
		String inSipSvr = inSipObj.getSipServer();
		Integer inSipAct = inSipObj.getnSipAct();
		String inSipPwd = inSipObj.getSipPwd();
		if ( inSipSvr.length() > 0 && inSipAct > 0 && 
			user.needIncomingSipAct() ) {
			UserDb.updateSipAccountByID(userID, sipSvr, sipAct+"", sipPwd, 
					inSipSvr, inSipAct+"", inSipPwd );
			if (Config.sipFixed == 0) {
				sipObj.setnSipAct(sipAct+1);
			}
			if (Config.incomingFixed == 0) {
				inSipObj.setnSipAct(inSipAct+1);
			}
		} else {
			UserDb.updateSipAccountByID(userID, sipSvr, sipAct+"", sipPwd, 
				"", "", "" );
			if (Config.sipFixed == 0) {
				sipObj.setnSipAct(sipAct+1);
			}
		}
		
		return true;
	}
	
	public static void distributeSipActToUser(int userID) {
		String osName = Utils.getOSName();
		if (osName.startsWith("Window")) {
			return;
		}
		UserModel user = UserCached.selectUserByID(userID);
		SipAccountModel sipObj = null;
		SipAccountModel inSipObj = null;
		if (Config.sipDispatchType == 0) {
			sipObj = new SipAccountModel(Config.sipServerIP, usedSipAct, Config.sipPwd);
			inSipObj = new SipAccountModel(Config.incomingSipIP, usedIncomingSipAct, Config.incomingSipPwd);
			updateUserSipAct(user, sipObj, inSipObj);
			usedSipAct = sipObj.getnSipAct();
			usedIncomingSipAct = inSipObj.getnSipAct();
		} else if (Config.sipDispatchType == 1) {
			
		} else if (Config.sipDispatchType == 2) {
			Integer comID = user.getBelongCompanyID();
			if ( companySipConfig.containsKey(comID) ) {
				SipConfigModel sipConfig = companySipConfig.get(comID);
				Integer sipAccount = 0;
				Integer inSipAct = 0;
				if ( comUsedSipAct.containsKey(comID) ) {
					sipAccount = comUsedSipAct.get(comID);
					inSipAct = comIncomingUsedSipAct.get(comID);
				} else {					
					if (sipConfig.getSipAccount().length() > 0) {
						sipAccount = Integer.parseInt(sipConfig.getSipAccount());
					}
					if (sipConfig.getInSipAccount().length() > 0) {
						inSipAct = Integer.parseInt(sipConfig.getInSipAccount());
					}
				}
				sipObj = new SipAccountModel(sipConfig.getSipServer(), sipAccount, sipConfig.getSipPwd() );
				inSipObj = new SipAccountModel(sipConfig.getInSipServer(), inSipAct, sipConfig.getInSipPwd() );

				updateUserSipAct(user, sipObj, inSipObj );
				comUsedSipAct.put(comID, sipObj.getnSipAct() );
				comIncomingUsedSipAct.put(comID, inSipObj.getnSipAct() );
			}
		}
	}
	
	private static void distributeSipByCityName() {
		
	}
	
	private static void distributeSipByCompany() {
		if (companySipConfig == null || companySipConfig.size() == 0) {
			return;
		}
		List<UserModel> allUsers = UserDb.selectAllUser();
		comUsedSipAct.clear();
		comIncomingUsedSipAct.clear();
		for (Integer comID : companySipConfig.keySet()) {
			SipConfigModel sipConfig = companySipConfig.get(comID);
			Integer sipAccount = 0;
			Integer inSipAct = 0;
			if (sipConfig.getSipAccount().length() > 0) {
				sipAccount = Integer.parseInt(sipConfig.getSipAccount());
			}
			if (sipConfig.getInSipAccount().length() > 0) {
				inSipAct = Integer.parseInt(sipConfig.getInSipAccount());
			}
			SipAccountModel sipObj = new SipAccountModel(sipConfig.getSipServer(), sipAccount, sipConfig.getSipPwd() );
			SipAccountModel inSipObj = new SipAccountModel(sipConfig.getInSipServer(), inSipAct, sipConfig.getInSipPwd() );
			for (UserModel user : allUsers) {
				if (user.getCompanyID() == 0) {
					continue;
				}
				if (user.getCompanyID() == comID || user.getBelongCompanyID() == comID) {
					updateUserSipAct(user, sipObj, inSipObj );
				}  //  end company id if
			}  // end on job use for
			comUsedSipAct.put(comID, sipObj.getnSipAct() );
			comIncomingUsedSipAct.put(comID, inSipObj.getnSipAct() );
		} // end for
		
	}
	
	private static void sendAllUserSipAccount() {
		List<UserModel> onjobUsers = UserDb.selectAllOnJobUser();
		for (UserModel user : onjobUsers) {
			NetMessageData sendMsg = new NetMessageData();
			JSONObject resJson = new JSONObject();
			resJson.put("resCode", 0);
			user.sipInfoToJson(resJson);
			resJson.put("userID", user.getId());
			sendMsg.setMsgBody(resJson.toJSONString());
			sendMsg.setMsgCmd(NetMessageData.Net_MODIFY_SIP);
			sendMsg.setUserID(user.getId());
			ResponseMsgQueue.addMsgToQueue(sendMsg);
		}
	}
	
}
